package com.itheima.health.config;

import com.itheima.health.common.RedisConstant;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author ：电麦腿
 * @date ：Created in 2022年08月01日
 * @description ：定时清理Redis中的图片缓存
 * @version: 1.0
 */
@Slf4j
@Component
public class ClearImageJob{
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private QiniuUtils qiniuUtils;

    /**
     * 定时从Redis中查询垃圾图片,并清理,每秒一次
     */
    @Scheduled(cron = "0/120 * * * * ? ")
    public void clearImg(){
        log.info("=====开启定时清理垃圾图片任务=====");
        //获取垃圾图片的Set集合
        Set difference=redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        //遍历所有key
        for (Object img:difference){
            //清除Redis中的垃圾图片
            redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES,img);
            String key=(String) img;
            //删除七牛云上的垃圾图片
            qiniuUtils.deleteFileFromQiniu(key);
        }
    }
}

/*
@Component  //定义任务实现类
@Slf4j
public class ClearImageJob {
    //清理前最小等待时间
    private static final Long MIN_DELETE_WAIT_TIME=10*60*;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private QiniuUtils qiniuUtils;
    @Autowired
    private SetMealService setMealService;
    @Scheduled(cron = "0 0 2 * * ?")//设置时间为凌晨两点进行垃圾图片删除
    public void executeInternal() throws JobExecutionException{
        log.info("[清理垃圾图片]开始......");
        //清理垃圾图片
        */
/*SetOperations setOperations = redisTemplate.opsForSet();
        setOperations.add("集合名","元素");
        BoundSetOperations ss=redisTemplate.boundSetOps("ss");
        ss.add("元素");*//*

        //查询来redis中的 暂存图片信息
        Set<String> set=redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).members();
        for (String img:set){
            try {
                System.out.println("截取图片:"+img);
                Long createTime=Long.valueOf(img.split("_",2)[0]);
                System.out.println(createTime);
                //判断一:等待时间是否大于清理前的最小等待时间;防止用户表单未提交,图片就被删除
                if (System.currentTimeMillis()-createTime < MIN_DELETE_WAIT_TIME ){
                    log.info("[清理垃圾图片]等待时间小于清理前的最小等待时间,暂不删除:{}");
                    continue;
                }
                //判断二:判断是否被使用
            }
        }
    }
}*/

